package node;

import lexer.LexType;
import parser.Parser;

import java.io.IOException;
import java.util.List;

public class AddExpNode extends ASTNode {
    public final String name = "<AddExp>";
    // AddExp → MulExp | AddExp ('+' | '-') MulExp
    // 改写文法
    // AddExp → MulExp { ('+' | '-') MulExp}
    private final List<MulExpNode> mulExpNodeList;
    private final List<String> addOpList;

    public AddExpNode(List<MulExpNode> mulExpNodeList, List<String> addOpList) {
        this.mulExpNodeList = mulExpNodeList;
        this.addOpList = addOpList;
    }

    public List<String> getAddOpList() {
        return addOpList;
    }

    public List<MulExpNode> getMulExpNodeList() {
        return mulExpNodeList;
    }

    @Override
    public void show() throws IOException {
        for (int i = 0; i < mulExpNodeList.size(); i++) {
            if (i < addOpList.size() + 1 && i != 0) {
                if (addOpList.get(i - 1).equals("+"))
                    Parser.parserWriter.write(LexType.PLUS + " " + "+" + "\n");
                else
                    Parser.parserWriter.write(LexType.MINU + " " + "-" + "\n");
            }

            mulExpNodeList.get(i).show();
            Parser.parserWriter.write(name + "\n");
        }
    }

    public int calculate() {
        // 确定当前AddExp是加减法计算，即一定可以被计算出具体的数值
        // 输入：List<MulExpNode> mulExpNodeList, List<String> addOpList
        // 输出：一个int类型的数字
        int result = mulExpNodeList.get(0).calculate();
        for (int i = 1; i < mulExpNodeList.size(); i++) {
            if (addOpList.get(i - 1).equals("+")) {
                result += mulExpNodeList.get(i).calculate();
            } else {
                result -= mulExpNodeList.get(i).calculate();
            }
        }
        return result;
    }

    public boolean canCaclulate() {
        for (MulExpNode mulExpNode : mulExpNodeList) {
            if (!mulExpNode.canCaclulate()) {
                return false;
            }
        }
        return true;
    }

}
